package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession{

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... args) throws Exception {
        // 使用SimpleExecutor.query()
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<Object> query = simpleExecutor.query(configuration, configuration.getMappedStatementMap().get(statementId), args);
        return (List<E>) query;
    }

    @Override
    public <E> E selectOne(String statementId, Object... args) throws Exception {
        List<Object> objectList = selectList(statementId, args);
        if(objectList.size() == 1){
            return (E) objectList.get(0);
        }else{
            throw new RuntimeException("查询结果为空或返回结果过多");
        }
    }

    @Override
    public int update(String statementId, Object... args) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        int i = simpleExecutor.update(this.configuration, this.configuration.getMappedStatementMap().get(statementId), args);
        return i;
    }


    @Override
    public <E> E getMapper(Class<?> clazz) {
        Object o = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // 根据正在调用的方法，判断需要调用selectList或者selectOne
                //
                String name = method.getName();
                String name1 = method.getDeclaringClass().getName();
                String statementId = name1 + "." + name;
                if("listUser".equals(name)){
                    return selectList(statementId, args);
                }else if("selectUser".equals(name)){
                    return selectOne(statementId, args);
                }else if(name.startsWith("insert") || name.startsWith("update") || name.startsWith("delete")){
                    return update(statementId,args);
                }else{
                    throw new RuntimeException("未匹配到相关代理方法");
                }
            }
        });
        return (E) o;
    }
}
